<template>
  <!--新的采购合同首页-->
  <div class="purchase-contract-index">
    <div class="btns" style="padding: 1em;margin-bottom: 1em;background:#fff">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="toAdd">添加</el-button>
      <el-input v-model="searchForm.contractName" type="text" size="small" placeholder="合同名" clearable/>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="toSearch">查询</el-button>
    </div>
    <div style="padding:1em;margin:1em 1em 0em 1em;background:#fff">
      <a-table
        :loading="loading"
        :data-source="tableData"
        size="small"
        :rowKey="record => record.id"
        :scroll="tableData.length>0?{x:1300}:{}">
        <a-table-column align="center" :width="140" key="contractName" title="合同名" data-index="contractName" />
        <a-table-column align="center" :width="160" key="contractNo" title="合同编号" data-index="contractNo" />
        <a-table-column align="center" :width="160"  key="time" title="生成时间" data-index="time">
          <template slot-scope="text, record, index">
            {{dateTimeFormat(text)}}
          </template>
        </a-table-column>
        <a-table-column align="center" :width="120" key="remark" title="备注" data-index="remark" />
        <a-table-column fixed="right" align="center" :width="400" key="action" title="操作">
          <template slot-scope="text, record, index">
            <el-button @click.native.stop="editContract(record)" icon="el-icon-edit" type="success" size="mini" style="padding: 7px 10px;">修改</el-button>
            <el-button @click.native.stop="toCheck(record)" v-if="record.firstAudit==null && record.secondAudit==null && record.threeAudit==null" type="success" icon="el-icon-s-promotion" size="mini" style="padding: 7px 10px;">送审</el-button>
            <el-button @click.native.stop="upload(record, index)" :loading="uploadLoading[index]" type="primary" size="mini" style="padding: 7px 10px;" icon="el-icon-upload">附件</el-button>
            <el-button @click.native.stop="deleteContract(record, index)" icon="el-icon-delete" type="danger" size="mini" style="padding: 7px 10px;">删除</el-button>
          </template>
        </a-table-column>
      </a-table>
    </div>
  </div>



</template>

<script>

    import '@/styles/auto-style.css'
    import XLSX from 'xlsx'
    import { dateTimeFormat } from '@/utils/format'
    import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
    import { beforeUpload, uploadStatusChange } from '@/utils/upload'
    import elDragDialog from '@/directive/el-drag-dialog'

    const fileUploadUrl = process.env.VUE_APP_BASE_API + 'file/uploadCache'


    export default {
        directives: { elDragDialog },

        name: "new.uve",

        data(){
            return{
                tableData: [],

                fileUploadUrl,

                contractNo: null,

                uploadForm: {},
                fileList: [],
                uploadKey: true,
                uploadDialogVisible: false,
                uploadSubmitLoading: false,

                uploadLoading: [],

                searchForm: {},
                contracts: [],
                contractsLoading: false,
                purchasePros: [],

                checkIcon: [
                    { color: '#909399', type: 'question-circle' },
                    { color: '#13ce66', type: 'check-circle' },
                    { color: '#ff4949', type: 'close-circle'},
                ],

                title: '',
                dialogVisible: false,
                form: {},

                rules: {
                    contractNo: [
                        { validator: validNo, trigger: 'blur'}
                    ],
                    contractName: [
                        { required: true, message: '不能为空', trigger: 'blur'}
                    ],
                    projectId: [
                        { required: true, message: '不能为空', trigger: 'blur'}
                    ],
                    paymentMethod: [
                        { required: true, message: '不能为空', trigger: 'blur'}
                    ],
                    payable: [
                        { required: true, pattern: /^(\-|\+)?\d+(\.\d+)?$/, message: '格式不正确', trigger: 'blur' }
                    ],
                    bond: [
                        { required: true, pattern: /^(\-|\+)?\d+(\.\d+)?$/, message: '格式不正确', trigger: 'blur' }
                    ],
                },

                toCheckDialogForm: {},
                checkDialogVisible: false,

                contractSupplies: [],
                contractSuppliesLoading: false,

                selectKey: '',
                currentContract: '',

                windowWidth: document.documentElement.clientWidth, // 屏幕实时宽度
            }
        },
        methods: {
            editContract(record) {
                this.form = record
                this.title = '修改'
                this.contractNo = record.contractNo
                console.log(record)
                this.dialogVisible = true
            },
            deleteContract(row, index){
                this.$confirm('是否确定删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    postActionByQueryString('/purchase/contract/deleteById',row)
                        .then(resp => {
                            this.$message({ message: resp.message, type: 'success' })
                            this.toSearch()
                            this.rowClick(row)
                        })
                })
            },
            uploadHandler() {
                if (this.uploadKey) {
                    this.uploadSubmitLoading = true
                    const fileList = this.fileList.map(item => {
                        console.log(item)
                        return { id: item.id, name: item.name, url: item.url, type: 5, operator: item.response.operator }
                    })
                    console.log(fileList)
                    let form = {}
                    form.purchaseContract = this.uploadForm
                    form.purchaseContract.operator = getUser()
                    form.fileList = fileList
                    postActionByJson('/purchase/contractManagement/uploadContractFile', form)
                        .then(resp=> {
                            this.$message({ message: resp.message, type: 'success' })
                        })
                        .finally(() => {
                            this.uploadSubmitLoading = false
                            this.uploadDialogVisible = false
                        })
                }else {
                    this.$message({ message: '文件上传未完成', type: 'warning' })
                }
            },
            beforeUpload,
            uploadStatusChange,
            upload(row, index) {
                this.fileList = []
                this.uploadLoading[index] = true
                getAction('/file/findByOtherId',{otherId: row.id, type: 5})
                    .then(resp => {
                        resp.data.map(item => {
                            let response = item
                            response.error = 0
                            response.fileId = response.id
                            response.fileName = response.name
                            this.fileList.push({
                                uid: 0-item.id,
                                name: item.name,
                                operator: item.operator,
                                status: 'done',
                                response: response,
                                url: response.url
                            })
                        })
                        this.uploadDialogVisible = true
                        this.uploadForm = row
                    })
                    .finally(()=>{
                        this.uploadLoading[index] = false
                    })
            },
            saveRecordHandler(form) {
                let params = this.form
                params.operator = getUser()
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        postActionByQueryString('/purchase/contract/saveOrUpdate', params)
                            .then( resp => {
                                this.$message({ message: resp.message, type: 'success' })
                                this.dialogVisible = false
                                this.toSearch()
                            })
                    }else {
                        console.log('error commit')
                        return false
                    }
                })
            },
            toAdd() {
                this.contractNo = null
                this.dialogVisible = true
                this.form = {}
                this.title = '新增采购合同'
            },
            toSearch() {
                let projectId = ''
                if (this.searchForm.purProjectId) {
                    projectId = this.searchForm.purProjectId
                }
                this.contractsLoading = true
                getAction('/purchase/contract/findByProjectId', { projectId: projectId, contractName: this.searchForm.contractName})
                .then(resp => {
                    this.contracts = resp.data
                    this.contractsLoading = false
                })
                .catch(() => {
                    this.contractsLoading = false
                })
            },
            dateTimeFormat,
            onSelectChange(selectedRowKeys, selectedRows) {
                const rows = selectedRows.map(item => {
                    if (item.quote.id) {
                        return item.quote.id
                    }
                })
                this.selectedRowKeys = rows
            },
        }
    }
</script>

<style lang="scss" scoped>
  .purchase-contract-index{

  }
</style>
